package com.lmf.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Callable;

/**
 * SpringMVC中的异步请求处理
 */
@Controller
public class AsyncController {

    @RequestMapping("/createOrder")
    @ResponseBody
    public DeferredResult<Object> creatOrder(){
        /*
         * 在创建DeferredResult对象时，可以像下面这样传入一些参数哟！
         *
         * 第一个参数（timeout）： 超时时间。限定（请求？）必须在该时间内执行完，如果超出时间限制，那么就会返回一段错误的提示信息（timeoutResult）
         * 第二个参数（timeoutResult）：超出时间限制之后，返回的错误提示信息
         */
        DeferredResult<Object> deferredResult = new DeferredResult<>();
        return deferredResult;
    }

    @RequestMapping("/async01")
    @ResponseBody
    public Callable<String> async(){
        System.out.println("主线程开始:" + Thread.currentThread() + "==>" + System.currentTimeMillis());
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("副线程开始:" + Thread.currentThread() + "==>" + System.currentTimeMillis());
                Thread.sleep(2000); // 线程睡上2秒
                System.out.println("副线程结束:" + Thread.currentThread() + "==>" + System.currentTimeMillis());
                // 响应给客户端一串字符串，即"Callable<String> async01()"
                return "Callable<String> async01()";
            }
        };
        System.out.println("主线程结束:" + Thread.currentThread() + "==>" + System.currentTimeMillis());
        return callable;
    }


}
